package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.service.GeneralService
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.sql.DataSource

/**
 *
 * @Title: cn.com.callback-apiCallDataXf
 * @Description:ngsapitask-sw avaya数据补录
 * @Author: yzh
 * @Date 2024/8/8 10:27
 *
 */
class apiCallDataXf implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCallDataXf.class);

    private static final String SQL = "insert into call_detail_xf_temp (rec_guid,ringingStartTime,ringingEndTime,talkingBeginTime,talkingEndTime,areatype,agentName,station,agent_id,ucid,firstAgentCDN,lastAgentCDN,firstAgentQueue,firstQueueBeginTime,firstQueueEndTime,toAgent,firstAgentAnswer,calltype,ani,dnis)" +
            "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse httpServletResponse) {
        DataSource dataSource1 = (DataSource) GeneralService.wac.getBean("dataSource");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource1);
        String callDataRes = "";
        try {
            String apipram = "";
            //获取接口地址
            String url = KHDBConfig.getAPIURL(eliteBean, "queryData");;
            //获取请求报文
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                apipram += line;
            }
            log.info("接收调用POST报文信息：" + apipram);
            //生成头部
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json;");
            JSONObject inJson = JSONObject.fromObject(apipram);
            String startTime = inJson.getString("startTime");
            String endTime = inJson.getString("endTime");
            //递归获取两日期间的所有时间
            String dateSplitSql = "DECLARE @StartDate DATE = ?;\n" +
                    "DECLARE @EndDate DATE = ?;\n" +
                    "WITH DateSequence AS (\n" +
                    "    SELECT @StartDate AS DateValue\n" +
                    "    UNION ALL\n" +
                    "    SELECT DATEADD(day, 1, DateValue)\n" +
                    "    FROM DateSequence\n" +
                    "    WHERE DATEADD(day, 1, DateValue) <= @EndDate\n" +
                    ")\n" +
                    "SELECT DateValue\n" +
                    "FROM DateSequence\n" +
                    "OPTION (MAXRECURSION 0)"
            List<Map<String,Object>> dateSplitList = jdbcTemplate.queryForList(dateSplitSql,startTime,endTime);
            //按天分批写入数据
            for (Map<String,Object> mp : dateSplitList) {
                String paramStartTime = mp.get("DateValue").toString() + " 00:00:00";
                String paramEndTime = mp.get("DateValue").toString() + " 23:59:59";
                log.debug("请求开始时间：" + paramStartTime);
                log.debug("请求结束时间：" + paramEndTime);
                //拼接接口请求参数
                JSONObject json = new JSONObject();
                json.put("startTime", paramStartTime);
                json.put("endTime", paramEndTime);
                //调用接口
                callDataRes = Util.doHttpPostUseHead(url, json.toString(), "UTF-8", 10000, 0, headMap);
                JSONArray jsonArray = JSONArray.fromObject(callDataRes);
                ArrayList<Object[]> batchArgs = new ArrayList<>();
                long startTimes = System.currentTimeMillis();
                int flag = 0;
                int executeCount = 0;//执行数量
                int jyCount = 0; //剩于数量
                int executeTotal = 0; //执行总次数
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);
                    String station=GetSFJV(jsonObj,"station");
                    String uuid = UUID.randomUUID().toString();
                    String ringingStartTime = GetSFJV(jsonObj,"ringingStartTime");
                    String ringingEndTime = GetSFJV(jsonObj,"ringingEndTime");
                    String talkingBeginTime = GetSFJV(jsonObj,"talkingBeginTime");
                    String talkingEndTime = GetSFJV(jsonObj,"talkingEndTime");
                    String areatype = GetSFJV(jsonObj,"areatype");
                    String agentName = GetSFJV(jsonObj,"agentName");
                    // String station = jsonObj.optString("station","");
                    String agent_id = GetSFJV(jsonObj,"agent_id");
                    String ucid = GetSFJV(jsonObj,"ucid");
                    String firstAgentCDN = GetSFJV(jsonObj,"firstAgentCDN");
                    String lastAgentCDN = GetSFJV(jsonObj,"lastAgentCDN");
                    String firstAgentQueue = GetSFJV(jsonObj,"firstAgentQueue");
                    String firstQueueBeginTime = GetSFJV(jsonObj,"firstQueueBeginTime");
                    String firstQueueEndTime = GetSFJV(jsonObj,"firstQueueEndTime");
                    String toAgent = GetSFJV(jsonObj,"toAgent");
                    String firstAgentAnswer = GetSFJV(jsonObj,"firstAgentAnswer");
                    String calltype = GetSFJV(jsonObj,"calltype");
                    String ani = GetSFJV(jsonObj,"ani");
                    String dnis = GetSFJV(jsonObj,"dnis");
                    Object[] objects = [uuid, ringingStartTime, ringingEndTime, talkingBeginTime, talkingEndTime, areatype, agentName, station, agent_id, ucid, firstAgentCDN, lastAgentCDN, firstAgentQueue, firstQueueBeginTime, firstQueueEndTime, toAgent, firstAgentAnswer, calltype, ani, dnis];
                    batchArgs.add(objects);
                    flag++;
                    executeCount++;
                    jyCount = jsonArray.size() - executeCount;
                    //每满一小批次100条提交一次
                    if (jsonArray.size() > 100 && flag == 100) {
                        executeTotal = executeTotal + 1;
                        jdbcTemplate.batchUpdate(SQL, batchArgs);
                        long spendTime = System.currentTimeMillis() - startTimes;
                        log.info(mp.get("DateValue") + "-" + executeTotal + "批量插入 " + flag + "条数据,剩于" + jyCount + "条,耗时：" + spendTime + "毫秒");
                        flag = 0;//标记初始化
                        batchArgs.clear();//清空集合
                    } else if (jyCount == 0){
                        int count =  jsonArray.size() - (executeTotal * 100);
                        jdbcTemplate.batchUpdate(SQL, batchArgs);
                        executeTotal = executeTotal + 1;
                        long spendTime = System.currentTimeMillis() - startTimes;
                        log.info(mp.get("DateValue") + "-" + executeTotal + "批量插入 " + count + "条数据,剩于" + jyCount + "条,总计：" + executeCount + "耗时：" + spendTime + "毫秒");
                        flag = 0;//标记初始化
                        batchArgs.clear();//清空集合
                    }
                }
            }
        } catch (Exception e) {
            log.error("数据补录异常：" + e.getMessage());
        }
        return "处理完成";
    }

    /**
     * 处理空JSON数据
     * @param inJson
     * @param getKey
     * @return
     */
    public static String GetSFJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}
